#version 330 core

out vec4 fragColor;

struct Material {
    sampler2D diffuse;
    sampler2D specular;
    float     shininess;
};

struct DirLight {
    vec3 direction;

    vec3 ambient;    // 环境光照
    vec3 diffuse;    // 漫反射光照
    vec3 specular;   // 镜面光照
};

in vec3 fragPos;
in vec3 normal;
in vec2 texCoords;

uniform vec3       u_viewPos;
uniform Material   u_material1;
uniform DirLight   u_dirLight;

vec3 calc_dir_light(DirLight light, Material material, vec3 normal, vec3 viewDir);

void main()
{
    vec3 norm = normalize(normal);
    vec3 viewDir = normalize(u_viewPos - fragPos);

    vec3 result = calc_dir_light(u_dirLight, u_material1, norm, viewDir);
    fragColor = vec4(result, 1.0);
}

vec3 calc_dir_light(DirLight light, Material material, vec3 normal, vec3 viewDir)
{
    vec3 lightDir = normalize(-light.direction);
    // 漫反射着色
    float diff = max(dot(normal, lightDir), 0.0);
    // 镜面光着色
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    // 合并结果
    vec3 ambient  = light.ambient  * vec3(texture(material.diffuse, texCoords));
    vec3 diffuse  = light.diffuse  * diff * vec3(texture(material.diffuse, texCoords));
    vec3 specular = light.specular * spec * vec3(texture(material.specular, texCoords));
    return (ambient + diffuse + specular);
}